package imp

import (
	sqlc "bgs/db/sqlc"
	storeGrpc "bgs/grpc/gen/service/store"
	"bgs/grpc/gen/shared/message"
	storeService "bgs/service/store"
	"bgs/util"
	"context"
	"database/sql"
	"fmt"
)

/****************************************************************************************/
/*                               store entity of helper                                 */
/****************************************************************************************/

func transformStoreEntityToPb(ptr *sqlc.Store) *storeGrpc.StoreEntity {
	return &storeGrpc.StoreEntity{
		Id:            ptr.ID,
		Name:          ptr.Name,
		BrandId:       ptr.BrandID,
		Intro:         ptr.Intro.String,
		Pic:           ptr.Pic.String,
		HomepageBg:    ptr.HomepageBg.String,
		Tel:           ptr.Tel.String,
		Opened:        sqlc.GoTimeToPBTimestamp(ptr.Opened),
		DistributorId: ptr.DistributorID.Int64,
	}
}

/****************************************************************************************/
/*                               store entity of cmd                                    */
/****************************************************************************************/

// OpenDistributeStore 开通分销门店
func (s *StoreAPIService) OpenDistributeStore(ctx context.Context, req *storeGrpc.OpenDistributeStoreRequest) (res *storeGrpc.OpenDistributeStoreResponse, err error) {
	slog := s.NewContextLogger(ctx)
	slog.Infof("storeImp->OpenNew:%v", req)

	res = &storeGrpc.OpenDistributeStoreResponse{
		OpRet: &message.OperationResult{
			Success: true,
			Code:    0,
		},
	}

	var storePtr *sqlc.Store
	err = s.dao.NewTxRunner().SqlcExecTx(ctx, func(q *sqlc.Queries) (err error) {

		brandID := req.BrandId
		userID := req.UserId
		distributorID := req.DistributorId
		userPtr, err := s.userService.GetUserPtr(ctx, q, userID)
		if err != nil {
			return
		}
		if !userPtr.Mobile.Valid {
			err = fmt.Errorf("user mobile is invalid")
			return
		}

		distributorPtr, sqlErr := s.brandService.GetDistributorPtrByUserIDAndBrandID(ctx, q, userID, brandID)
		if sqlErr != nil {
			if sql.ErrNoRows == sqlErr {
				err = fmt.Errorf("用户还不是品牌的分销员")
			} else {
				err = sqlErr
			}
			return
		}

		if distributorID != distributorPtr.ID {
			err = fmt.Errorf("分销员不匹配")
			return
		}

		storePtr, err = s.storeService.OpenDistributeStore(ctx, q, &storeService.OpenDistributeStoreParam{
			UserID:        userID,
			Name:          req.Name,
			BrandID:       brandID,
			Intro:         req.Intro,
			Pic:           req.Pic,
			DistributorID: distributorID,
		})
		if err != nil {
			return
		}
		slog.Info("1 开通分销门店 ok")
		return
	})
	if err != nil {
		res.OpRet = &message.OperationResult{
			Success: false,
			Code:    400,
			Msg:     err.Error(),
		}
		return
	}
	res.Store = transformStoreEntityToPb(storePtr)
	return
}

// UpdateStoreInfo 更新门店信息
func (s *StoreAPIService) UpdateStoreInfo(ctx context.Context, req *storeGrpc.UpdateStoreInfoRequest) (res *storeGrpc.UpdateStoreInfoResponse, err error) {
	slog := s.NewContextLogger(ctx)
	slog.Infof("storeImp->UpdateStoreInfo:%v", req)

	res = &storeGrpc.UpdateStoreInfoResponse{
		OpRet: &message.OperationResult{
			Success: true,
			Code:    0,
		},
	}

	var storePtr *sqlc.Store
	err = s.dao.NewTxRunner().SqlcExecTx(ctx, func(q *sqlc.Queries) (err error) {
		storeID := req.Id
		storePtr, err = s.storeService.UpdateStoreInfo(ctx, q, &storeService.UpdateStoreInfoParam{
			StoreID:    storeID,
			Name:       req.Name,
			Intro:      req.Intro,
			Pic:        req.Pic,
			HomepageBg: req.HomepageBg,
			Tel:        req.Tel,
		})
		if err != nil {
			return
		}
		slog.Info("1 更新门店信息 ok")
		return
	})
	if err != nil {
		res.OpRet = &message.OperationResult{
			Success: false,
			Code:    400,
			Msg:     err.Error(),
		}
		return
	}
	res.Store = transformStoreEntityToPb(storePtr)
	return
}

/****************************************************************************************/
/*                               store entity of query                                  */
/****************************************************************************************/

// GetStore 获取单个门店
func (s *StoreAPIService) GetStore(ctx context.Context, req *storeGrpc.GetStoreRequest) (res *storeGrpc.GetStoreResponse, err error) {
	slog := s.NewContextLogger(ctx)
	slog.Infof("storeImp->GetStore:%v", req)
	res = &storeGrpc.GetStoreResponse{
		OpRet: &message.OperationResult{
			Success: true,
			Code:    0,
		},
	}
	q := s.dao.Q
	storeID := req.Id
	storePtr, err := s.storeService.GetStorePtr(ctx, q, storeID)
	if err != nil {
		return
	}
	res.Store = transformStoreEntityToPb(storePtr)
	return
}

// GetStore 获取单个门店的拥有者
func (s *StoreAPIService) GetStoreOwner(ctx context.Context, req *storeGrpc.GetStoreOwnerRequest) (res *storeGrpc.GetStoreOwnerResponse, err error) {
	slog := s.NewContextLogger(ctx)
	slog.Infof("storeImp->GetStoreOwner:%v", req)
	res = &storeGrpc.GetStoreOwnerResponse{
		OpRet: &message.OperationResult{
			Success: true,
			Code:    0,
		},
	}
	q := s.dao.Q
	storeID := req.Id
	userID, err := s.storeService.GetStoreOwner(ctx, q, storeID)
	if err != nil {
		return
	}
	res.UserId = userID
	return
}

/****************************************************************************************/
/*                               store joins entity of query                            */
/****************************************************************************************/

func transformStoreWithStatEntityToPb(ptr *sqlc.GetStoreWithStatRow) *storeGrpc.StoreWithStatEntity {
	return &storeGrpc.StoreWithStatEntity{
		Id:            ptr.ID,
		Name:          ptr.Name,
		BrandId:       ptr.BrandID,
		Intro:         ptr.Intro.String,
		Pic:           ptr.Pic.String,
		HomepageBg:    ptr.HomepageBg.String,
		Tel:           ptr.Tel.String,
		Opened:        sqlc.GoTimeToPBTimestamp(ptr.Opened),
		DistributorId: ptr.DistributorID.Int64,
		// stat
		FansCount:                  ptr.FansCount,
		PublishActivityCount:       ptr.PublishActivityCount,
		SpokesmanCount:             ptr.SpokesmanCount,
		EndorseRequestToAuditCount: ptr.EndorseRequestToAuditCount,
		OrderCount:                 ptr.OrderCount,
		SaleAmount:                 ptr.SaleAmount,
		RefundAmount:               ptr.RefundAmount,
		DistributeAmount:           ptr.DistributeAmount,
		OrderBonus:                 ptr.OrderBonus,
		RefundOrderBonus:           ptr.RefundAmount,
	}
}

func transformStoreWithStatAndAccountEntityToPb(ptr *sqlc.GetStoreWithStatAndAccountRow) *storeGrpc.StoreWithStatAndAccountEntity {
	return &storeGrpc.StoreWithStatAndAccountEntity{
		Id:            ptr.ID,
		Name:          ptr.Name,
		BrandId:       ptr.BrandID,
		Intro:         ptr.Intro.String,
		Pic:           ptr.Pic.String,
		HomepageBg:    ptr.HomepageBg.String,
		Tel:           ptr.Tel.String,
		Opened:        sqlc.GoTimeToPBTimestamp(ptr.Opened),
		DistributorId: ptr.DistributorID.Int64,
		// stat
		FansCount:                  ptr.FansCount,
		PublishActivityCount:       ptr.PublishActivityCount,
		SpokesmanCount:             ptr.SpokesmanCount,
		EndorseRequestToAuditCount: ptr.EndorseRequestToAuditCount,
		OrderCount:                 ptr.OrderCount,
		SaleAmount:                 ptr.SaleAmount,
		RefundAmount:               ptr.RefundAmount,
		DistributeAmount:           ptr.DistributeAmount,
		OrderBonus:                 ptr.OrderBonus,
		RefundOrderBonus:           ptr.RefundAmount,
		// account
		AvailableAmount:   ptr.AvailableAmount,
		PendingAmount:     ptr.PendingAmount,
		WithdrawingAmount: ptr.WithdrawingAmount,
		WithdrawedAmount:  ptr.WithdrawedAmount,
	}
}

func transformStoreWithStatAndEndorsementForUserEntityToPb(ptr *sqlc.GetStoreWithStatAndEndorsementForUserRow) *storeGrpc.StoreWithStatAndEndorsementEntity {
	return &storeGrpc.StoreWithStatAndEndorsementEntity{
		Id:            ptr.ID,
		Name:          ptr.Name,
		BrandId:       ptr.BrandID,
		Intro:         ptr.Intro.String,
		Pic:           ptr.Pic.String,
		HomepageBg:    ptr.HomepageBg.String,
		Tel:           ptr.Tel.String,
		Opened:        sqlc.GoTimeToPBTimestamp(ptr.Opened),
		DistributorId: ptr.DistributorID.Int64,
		// stat
		FansCount:                  ptr.FansCount,
		PublishActivityCount:       ptr.PublishActivityCount,
		SpokesmanCount:             ptr.SpokesmanCount,
		EndorseRequestToAuditCount: ptr.EndorseRequestToAuditCount,
		OrderCount:                 ptr.OrderCount,
		SaleAmount:                 ptr.SaleAmount,
		RefundAmount:               ptr.RefundAmount,
		DistributeAmount:           ptr.DistributeAmount,
		OrderBonus:                 ptr.OrderBonus,
		RefundOrderBonus:           ptr.RefundAmount,
		// endorsement
		IsEndorsementEntranceDisplay: ptr.IsEndorsementEntranceDisplay,
		EndorseSpokesmanId:           ptr.EndorseSpokesmanID,
	}
}
func transformListStoreWithStatsByUserIDAsDistributorRowEntityToPb(o sqlc.ListStoreWithStatsByUserIDAsDistributorRow) *storeGrpc.StoreWithStatEntity {
	return &storeGrpc.StoreWithStatEntity{
		Id:            o.ID,
		Name:          o.Name,
		BrandId:       o.BrandID,
		Intro:         o.Intro.String,
		Pic:           o.Pic.String,
		HomepageBg:    o.HomepageBg.String,
		Tel:           o.Tel.String,
		Opened:        sqlc.GoTimeToPBTimestamp(o.Opened),
		DistributorId: o.DistributorID.Int64,
		// stat
		FansCount:                  o.FansCount,
		PublishActivityCount:       o.PublishActivityCount,
		SpokesmanCount:             o.SpokesmanCount,
		EndorseRequestToAuditCount: o.EndorseRequestToAuditCount,
		OrderCount:                 o.OrderCount,
		SaleAmount:                 o.SaleAmount,
		RefundAmount:               o.RefundAmount,
		DistributeAmount:           o.DistributeAmount,
		OrderBonus:                 o.OrderBonus,
		RefundOrderBonus:           o.RefundAmount,
	}
}

func mapListStoreWithStatsByUserIDAsDistributorRowEntityToPb(list []sqlc.ListStoreWithStatsByUserIDAsDistributorRow, f func(sqlc.ListStoreWithStatsByUserIDAsDistributorRow) *storeGrpc.StoreWithStatEntity) []*storeGrpc.StoreWithStatEntity {
	r := make([]*storeGrpc.StoreWithStatEntity, len(list))
	for i, item := range list {
		r[i] = f(item)
	}
	return r
}

/****************************************************************************************/
/*                               store Joins entity of query                            */
/****************************************************************************************/

// GetStoreWithStat 获取单个门店及其统计信息
func (s *StoreAPIService) GetStoreWithStat(ctx context.Context, req *storeGrpc.GetStoreWithStatRequest) (res *storeGrpc.GetStoreWithStatResponse, err error) {
	slog := s.NewContextLogger(ctx)
	slog.Infof("storeImp->GetStoreWithStat:%v", req)
	res = &storeGrpc.GetStoreWithStatResponse{
		OpRet: &message.OperationResult{
			Success: true,
			Code:    0,
		},
	}
	q := s.dao.Q
	storeID := req.Id
	storeWithStatPtr, err := s.storeService.GetStoreWithStatPtr(ctx, q, storeID)
	if err != nil {
		return
	}
	res.StoreWithStat = transformStoreWithStatEntityToPb(storeWithStatPtr)
	return
}

// GetStoreWithStatAndAccount 获取单个门店及其统计和账户信息
func (s *StoreAPIService) GetStoreWithStatAndAccount(ctx context.Context, req *storeGrpc.GetStoreWithStatAndAccountRequest) (res *storeGrpc.GetStoreWithStatAndAccountResponse, err error) {
	slog := s.NewContextLogger(ctx)
	slog.Infof("storeImp->GetStoreWithStatAndAccount:%v", req)
	res = &storeGrpc.GetStoreWithStatAndAccountResponse{
		OpRet: &message.OperationResult{
			Success: true,
			Code:    0,
		},
	}
	q := s.dao.Q
	storeID := req.Id
	storeWithStatAndAccountPtr, err := s.storeService.GetStoreWithStatAndAccountPtr(ctx, q, storeID)
	if err != nil {
		return
	}
	res.StoreWithStatAndAccount = transformStoreWithStatAndAccountEntityToPb(storeWithStatAndAccountPtr)
	return
}

// GetStoreWithStatAndEndorsementForUser 获取单个门店信息+门店统计信息+门店招募信息
func (s *StoreAPIService) GetStoreWithStatAndEndorsementForUser(ctx context.Context, req *storeGrpc.GetStoreWithStatAndEndorsementForUserRequest) (res *storeGrpc.GetStoreWithStatAndEndorsementForUserResponse, err error) {
	slog := s.NewContextLogger(ctx)
	slog.Infof("storeImp->GetStoreWithStatAndEndorsementForUser:%v", req)
	res = &storeGrpc.GetStoreWithStatAndEndorsementForUserResponse{
		OpRet: &message.OperationResult{
			Success: true,
			Code:    0,
		},
	}
	q := s.dao.Q
	storeID := req.Id
	userID := req.UserId
	storeWithStatAndEndorsementPtr, err := s.storeService.GetStoreWithStatAndEndorsementPtrForUser(ctx, q, storeID, userID)
	if err != nil {
		return
	}
	res.StoreWithStatAndEndorsement = transformStoreWithStatAndEndorsementForUserEntityToPb(storeWithStatAndEndorsementPtr)
	return
}

// ListStoreWithStatByUserIDAsDistributor  获取未开通分销门店的分销员的列表
func (s *StoreAPIService) ListStoreWithStatByUserIDAsDistributor(ctx context.Context, req *storeGrpc.ListStoreWithStatByUserIDAsDistributorRequest) (res *storeGrpc.ListStoreWithStatByUserIDAsDistributorResponse, err error) {
	slog := s.NewContextLogger(ctx)
	slog.Infof("storeImp->ListStoreWithStatByUserIDAsDistributor:%v", req)

	res = &storeGrpc.ListStoreWithStatByUserIDAsDistributorResponse{
		OpRet: &message.OperationResult{
			Success: true,
			Code:    0,
		},
	}
	q := s.dao.Q
	userID := req.UserId

	total, err := q.CountStoreWithStatsByUserIDAsDistributor(ctx, userID)
	if err != nil {
		return
	}
	if total == 0 {
		// 不用继续调用listfunc
		return
	}

	rows, err := s.dao.Q.ListStoreWithStatsByUserIDAsDistributor(ctx, sqlc.ListStoreWithStatsByUserIDAsDistributorParams{
		Limit:  req.Limit,
		Offset: req.Offset,
		UserID: userID,
	})
	if err != nil {
		return
	}
	res.Total = total
	res.StoreWithStats = mapListStoreWithStatsByUserIDAsDistributorRowEntityToPb(rows, transformListStoreWithStatsByUserIDAsDistributorRowEntityToPb)
	return
}

/****************************************************************************************/
/*                            store account of helper                                   */
/****************************************************************************************/

func transformStoreAccountWithdrawApplymentEntityToPb(o sqlc.StoreAccountWithdrawApplyment) *storeGrpc.StoreAccountWithdrawApplymentEntity {
	return &storeGrpc.StoreAccountWithdrawApplymentEntity{
		Id:         o.ID,
		StoreId:    o.StoreID,
		Target:     o.Target,
		Applied:    sqlc.GoTimeToPBTimestamp(o.Applied),
		Amount:     o.Amount,
		Remark:     o.Remark,
		ApplyState: o.ApplyState,
	}
}

func mapStoreAccountWithdrawApplymentEntityToPb(list []sqlc.StoreAccountWithdrawApplyment, f func(sqlc.StoreAccountWithdrawApplyment) *storeGrpc.StoreAccountWithdrawApplymentEntity) []*storeGrpc.StoreAccountWithdrawApplymentEntity {
	r := make([]*storeGrpc.StoreAccountWithdrawApplymentEntity, len(list))
	for i, item := range list {
		r[i] = f(item)
	}
	return r
}

/****************************************************************************************/
/*                            store account of cmd                                      */
/****************************************************************************************/

// CreateStoreAccountWithdrawApplyment 创建提现申请
func (s *StoreAPIService) CreateStoreAccountWithdrawApplyment(ctx context.Context, req *storeGrpc.CreateStoreAccountWithdrawApplymentRequest) (res *storeGrpc.CreateStoreAccountWithdrawApplymentResponse, err error) {
	slog := s.NewContextLogger(ctx)
	slog.Infof("storeImp->CreateStoreAccountWithdrawApplyment:%v", req)
	res = &storeGrpc.CreateStoreAccountWithdrawApplymentResponse{
		OpRet: &message.OperationResult{
			Success: true,
			Code:    0,
		},
	}

	storeID := req.StoreId
	var storeAccountWithdrawApplymentPtr *sqlc.StoreAccountWithdrawApplyment
	err = s.dao.NewTxRunner().SqlcExecTx(ctx, func(q *sqlc.Queries) (err error) {

		storeAccountWithdrawApplymentPtr, err = s.storeService.SubmitAccountWithdrawApplyment(ctx, q, storeService.SubmitAccountWithdrawApplymentParam{
			StoreID:  storeID,
			Target:   sqlc.EmWithdrawTarget(req.Target), // 目前仅支持提现到微信零钱
			Amount:   req.Amount,
			RealName: req.RealName,
			IdCardNo: req.IdCardNo,
			Remark:   req.Remark,
		})

		if err != nil {
			return err
		}

		return
	})

	if err != nil {
		res.OpRet = &message.OperationResult{
			Success: false,
			Code:    400,
			Msg:     err.Error(),
		}
		return
	}
	res.StoreAccountWithdrawApplyment = transformStoreAccountWithdrawApplymentEntityToPb(*storeAccountWithdrawApplymentPtr)
	return
}

// ListStoreAccountWithdrawApplyments 分页获取多条提现记录
func (s *StoreAPIService) ListStoreAccountWithdrawApplyments(ctx context.Context, req *storeGrpc.ListStoreAccountWithdrawApplymentsRequest) (res *storeGrpc.ListStoreAccountWithdrawApplymentsResponse, err error) {
	slog := s.NewContextLogger(ctx)
	slog.Infof("storeImp->ListStoreAccountWithdrawApplyments:%v", req)

	res = &storeGrpc.ListStoreAccountWithdrawApplymentsResponse{
		OpRet: &message.OperationResult{
			Success: true,
			Code:    0,
		},
	}
	q := s.dao.Q
	storeID := req.StoreId

	total, err := q.CountStoreAccountWithdrawApplymentsByStoreID(ctx, storeID)
	if err != nil {
		return
	}

	if total == 0 {
		// 不用继续调用listfunc
		return
	}

	userAccountWithdrawApplyments, err := q.ListStoreAccountWithdrawApplymentsByStoreID(ctx, sqlc.ListStoreAccountWithdrawApplymentsByStoreIDParams{
		Limit:   req.Limit,
		Offset:  req.Offset,
		StoreID: storeID,
	})
	if err != nil {
		return
	}
	res.Total = total
	res.StoreAccountWithdrawApplyments = mapStoreAccountWithdrawApplymentEntityToPb(userAccountWithdrawApplyments, transformStoreAccountWithdrawApplymentEntityToPb)
	return
}

/****************************************************************************************/
/*                            store_account_log entity of helper                        */
/****************************************************************************************/

func transformStoreAccountLogEntityToPb(o sqlc.StoreAccountLog) *message.AccountLogInfo {
	return &message.AccountLogInfo{
		Id:       o.ID,
		Logged:   sqlc.GoTimeToPBTimestamp(o.Logged),
		Category: o.Category,
		Amount:   o.Amount,
		Subject:  o.Subject,
		ExtInfo:  o.ExtInfo,
	}
}

func mapStoreAccountLogEntityToPb(list []sqlc.StoreAccountLog, f func(sqlc.StoreAccountLog) *message.AccountLogInfo) []*message.AccountLogInfo {
	r := make([]*message.AccountLogInfo, len(list))
	for i, item := range list {
		r[i] = f(item)
	}
	return r
}

/****************************************************************************************/
/*                            store_account_log of query                                */
/****************************************************************************************/

// ListStoreAccountLogs  获取门店资金明细
func (s *StoreAPIService) ListStoreAccountLogs(ctx context.Context, req *storeGrpc.ListStoreAccountLogsRequest) (res *storeGrpc.ListStoreAccountLogsResponse, err error) {
	slog := s.NewContextLogger(ctx)
	slog.Infof("storeImp->ListStoreAccountLogs:%v", req)
	res = &storeGrpc.ListStoreAccountLogsResponse{
		OpRet: &message.OperationResult{
			Success: true,
			Code:    0,
		},
	}
	q := s.dao.Q
	ts := sqlc.PBTimestampToGoTime(req.Ts)
	begin := sqlc.PBTimestampToGoTime(req.Begin)
	end := sqlc.PBTimestampToGoTime(req.End)
	storeID := req.StoreId

	total, err := q.CountStoreAccountLogsByStoreID(ctx, sqlc.CountStoreAccountLogsByStoreIDParams{
		Created: ts,
		Begin:   begin,
		End:     end,
		StoreID: storeID,
	})
	if err != nil {
		return
	}

	if total == 0 {
		// 不用继续调用listfunc
		return
	}
	brandAccountLogs, err := q.ListStoreAccountLogsByStoreID(ctx, sqlc.ListStoreAccountLogsByStoreIDParams{
		Limit:   req.Limit,
		Offset:  req.Offset,
		Created: ts,
		Begin:   begin,
		End:     end,
		StoreID: storeID,
	})
	if err != nil {
		return
	}
	res.Total = total
	res.AccountLogs = mapStoreAccountLogEntityToPb(brandAccountLogs, transformStoreAccountLogEntityToPb)
	return
}

// AggrStoreAccountLogsToInOut 统计门店资金的收入与支出
func (s *StoreAPIService) AggrStoreAccountLogsToInOut(ctx context.Context, req *storeGrpc.AggrStoreAccountLogsToInOutRequest) (res *storeGrpc.AggrStoreAccountLogsToInOutResponse, err error) {
	slog := s.NewContextLogger(ctx)
	slog.Infof("storeImp->AggrStoreAccountLogsToInOut:%v", req)

	res = &storeGrpc.AggrStoreAccountLogsToInOutResponse{
		OpRet: &message.OperationResult{
			Success: true,
			Code:    0,
		},
	}
	q := s.dao.Q

	aggrRet, err := q.AggrStoreAccountLogsToInOut(ctx, sqlc.AggrStoreAccountLogsToInOutParams{
		Begin:   sqlc.PBTimestampToGoTime(req.Begin),
		End:     sqlc.PBTimestampToGoTime(req.End),
		StoreID: req.StoreId,
	})
	if err != nil {
		return
	}
	res.Income = aggrRet.Income
	res.Outlay = aggrRet.Outlay
	return
}

/****************************************************************************************/
/*                            store_endorsement entity of helper                        */
/****************************************************************************************/

func transformStoreEndorsementToPb(o sqlc.StoreEndorsement) *storeGrpc.StoreEndorsementEntity {
	return &storeGrpc.StoreEndorsementEntity{
		StoreId:              o.StoreID,
		IsOpen:               o.IsOpen,
		SpokesmanTitle:       o.SpokesmanTitle,
		UserStratified:       o.UserStratified,
		ConsumerLowerExpense: o.ConsumerLowerExpense.Int32,
		NeedApplyInfo:        o.NeedApplyInfo,
		ApplyInfoFields:      o.ApplyInfoFields,
		IsEntranceDisplay:    o.IsEntranceDisplay,
		IsAutoApproved:       o.IsAutoApproved,
	}
}

/****************************************************************************************/
/*                            store_endorsement entity of cmd                           */
/****************************************************************************************/

// UpsertStoreEndorsement 插入/更新门店代言设置
func (s *StoreAPIService) UpsertStoreEndorsement(ctx context.Context, req *storeGrpc.UpsertStoreEndorsementRequest) (res *storeGrpc.UpsertStoreEndorsementResponse, err error) {
	slog := s.NewContextLogger(ctx)
	slog.Infof("storeImp->UpsertStoreEndorsement:%v", req)
	res = &storeGrpc.UpsertStoreEndorsementResponse{
		OpRet: &message.OperationResult{
			Success: true,
			Code:    0,
		},
	}
	q := s.dao.Q
	storeEndorsement, err := q.UpsertStoreEndorsement(ctx, sqlc.UpsertStoreEndorsementParams{
		StoreID:              req.StoreId,
		IsOpen:               req.IsOpen,
		SpokesmanTitle:       req.SpokesmanTitle,
		UserStratified:       req.UserStratified,
		ConsumerLowerExpense: sqlc.NInt32FromInt32(req.ConsumerLowerExpense),
		NeedApplyInfo:        req.NeedApplyInfo,
		ApplyInfoFields:      req.ApplyInfoFields,
		IsEntranceDisplay:    req.IsEntranceDisplay,
		IsAutoApproved:       req.IsAutoApproved,
	})
	if err != nil {
		res.OpRet = &message.OperationResult{
			Success: false,
			Code:    400,
			Msg:     err.Error(),
		}
		return
	}
	res.StoreEndorsement = transformStoreEndorsementToPb(storeEndorsement)
	return
}

/****************************************************************************************/
/*                            store_endorsement entity of query                         */
/****************************************************************************************/

// GetStoreEndorsementByStoreID  获取单个门店代言信息
func (s *StoreAPIService) GetStoreEndorsementByStoreID(ctx context.Context, req *storeGrpc.GetStoreEndorsementByStoreIDRequest) (res *storeGrpc.GetStoreEndorsementByStoreIDResponse, err error) {
	slog := s.NewContextLogger(ctx)
	slog.Infof("storeImp->GetStoreEndorsementByStoreID:%v", req)
	res = &storeGrpc.GetStoreEndorsementByStoreIDResponse{
		OpRet: &message.OperationResult{
			Success: true,
			Code:    0,
		},
	}
	storeEndorsement, sqlErr := s.dao.Q.GetStoreEndorsementByStoreID(ctx, req.StoreId)
	if sqlErr != nil {
		res.OpRet = &message.OperationResult{
			Success: false,
			Code:    util.Int32IfThenElse(sql.ErrNoRows == sqlErr, 404, 400),
			Msg:     sqlErr.Error(),
		}
		return
	}
	res.StoreEndorsement = transformStoreEndorsementToPb(storeEndorsement)
	return
}
